#include <cstdlib>
#include <cstdio>

#include <IceUtil/IceUtil.h>
#include <IceStorm/IceStorm.h>
#include "eventConsumer.h"

EventConsumer::EventConsumer(::Ice::CommunicatorPtr& c, const std::string& host)
{	
	comm = c;
	
	createConsumer(host);
}

EventConsumer::~EventConsumer()
{
	topic->unsubscribe(subscriber);
}

void EventConsumer::createConsumer(const std::string& host)
{	
	char aux[256];
	sprintf(aux, "DemoIceStorm/TopicManager:tcp -h %s -p 10000", host.c_str());
	
	IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(
	        comm->stringToProxy(aux));
    if(!manager)
    {
        std::cerr << "Invalid consumer proxy" << std::endl;
        exit(1);
    }

    try
    {
        topic = manager->retrieve("events");
    }
    catch(const IceStorm::NoSuchTopic&)
    {
        try
        {
            topic = manager->create("events");
        }
        catch(const IceStorm::TopicExists&)
        {
            std::cerr << "Temporary failure. try again." << std::endl;
			exit(1);
        }
    }

    Ice::ObjectAdapterPtr adapter = comm->createObjectAdapterWithEndpoints("MIDataAccessor.Subscriber", "default");

    Ice::Identity subId;
    subId.name = ::IceUtil::generateUUID();
 
    subscriber = adapter->add(this, subId);
    IceStorm::QoS qos;

    try
    {
        topic->subscribeAndGetPublisher(qos, subscriber);
    }
    catch(const IceStorm::AlreadySubscribed&)
    {
		std::cerr << "Error subscribing." << std::endl;
		exit(1);
    }
    adapter->activate();
}
